package day1;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import utility.Bytes2String;
import utility.JdbcUtils;

public class BlobTest {
	public static void main(String[] args) throws Exception {
		//add();
		query();
	}
	public static void add() throws Exception {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con=JdbcUtils.getConnection();
			String sql = "insert into blob_test(big_bit,bit1) values (?,?) ";
			ps=con.prepareStatement(sql);
			InputStream in=BlobTest.class.getClassLoader().getResourceAsStream("1.jpg");
			byte[] bytes=new byte[3];
			bytes[0]=1;
			bytes[2]=1;
			bytes[1]=1;
			ps.setBinaryStream(1, in);
			ps.setBytes(2, bytes);
			
			int i=ps.executeUpdate();
			System.out.println("i="+i);
		}finally{
			JdbcUtils.free(rs, ps, con);
		}
	}
	
	public static void query() throws Exception {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con=JdbcUtils.getConnection();
			String sql = "select big_bit,bit1 from blob_test ";
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				InputStream inputStream=rs.getBinaryStream(1);
				BufferedInputStream bis=new BufferedInputStream(inputStream);
				File file=new File("d:/out1.jpg");
				FileOutputStream fos=new FileOutputStream(file);
				BufferedOutputStream bos=new BufferedOutputStream(fos);
				byte[] buff=new byte[1024];
				int len;
				while((len=bis.read(buff))!=-1){
					bos.write(buff,0,len);
				}
				bos.close();
				bis.close();
				
				byte[] bytes=rs.getBytes(2);
				for(byte b:bytes){
					System.out.println(b);
				}
			}
			
		}finally{
			JdbcUtils.free(rs, ps, con);
		}
	}
}
